package online.hxstar.learn.udp;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.DatagramPacket;
import io.netty.channel.socket.nio.NioDatagramChannel;
import io.netty.util.CharsetUtil;
import online.hxstar.learn.util.AppUtils;

import java.net.InetSocketAddress;


/**
 * @author huxing
 * @date 2018-12-18 16:12
 */
public class ChineseProverbClient {
    public static void main(String[] args) throws InterruptedException {
        int port = AppUtils.getPort(args);
        new ChineseProverbClient().run(port);
    }

    private void run(int port) throws InterruptedException {
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(group)
                    .channel(NioDatagramChannel.class)
                    .option(ChannelOption.SO_BROADCAST, true)
                    .handler(new ChineseProverbClientHandler());
            Channel ch = bootstrap.bind(8756).sync().channel();
            // 向网段内的所有机器广播UDP消息
            ch.writeAndFlush(
                    new DatagramPacket(Unpooled.copiedBuffer("谚语字典查询?", CharsetUtil.UTF_8)
                            , new InetSocketAddress("171.16.1.136", port)))
                    .sync();
            if (!ch.closeFuture().await(15000)) {
                System.out.println("查询操时!!!!");
            }
        } finally {
            group.shutdownGracefully();
        }
    }
}
